//
//  ArticleDetailViewController.m
//  HYSmileiOS
//
//  Created by SMC-MAC on 16/6/7.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "ArticleDetailViewController.h"

#import "CommentModel.h"
#import "ArticleTableViewCell.h"
#import "CommentTableViewCell.h"
#import "heyou.h"
#import "HYImageBrowser.h"
#import "TestData.h"
#import "HYInputView.h"

@interface ArticleDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSArray<CommentModel*>* mCommentList;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) HYInputView *inputView;

@end

@implementation ArticleDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self prepareData];
    [self setupTableView];
    [self _setupSendMessageView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - setup send message view
- (void)_setupSendMessageView {
    HYInputView *tView = [[[NSBundle mainBundle] loadNibNamed:@"HYInputView" owner:self options:nil] firstObject];
    [self.view addSubview:tView];
    self.inputView = tView;
    
    tView.onTextEditDone = ^(NSString *content) {
        NSLog(@"edit content = %@", content);
    };
}

#pragma mark -- prepare data
- (void)prepareData {
    NSArray<CommentModel*>* list = [TestData getCommentList];
    self.mCommentList = list;
}

- (void)getDataFromServer {
    
}

/**
 *  下拉刷新
 */
- (void)headerRereshing {
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [ws.tableView reloadData];
        // 调用endRefreshing可以结束刷新状态
        [ws.tableView.mj_header endRefreshing];
    });
}

#pragma mark -- setup tableview
- (void)setupTableView {
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerXibWithClass:[ArticleTableViewCell class]];
    [self.tableView registerXibWithClass:[CommentTableViewCell class]];
    [self.tableView hy_disableTouchDelay];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger num = 1;
    
    if (self.mCommentList && self.mCommentList.count > 0) {
        num += 1;
    }
    
    return num;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger num = 0;
    
    if (section == 0) {
        num = 1;
    } else if (section == 1) {
        num = self.mCommentList.count;
    }
    
    return num;
}

#pragma mark - TableView height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 45.0f;
    
    NSInteger section = indexPath.section;
    if (section == 0) {
        NSString *identifier = NSStringFromClass([ArticleTableViewCell class]);
        WS(ws);
        height = [tableView fd_heightForCellWithIdentifier:identifier cacheByIndexPath:indexPath configuration:^(id cell) {
            [ws configTableViewCell:cell forIndex:indexPath downloadImage:NO];
        }];
    } else if (section == 1) {
        NSString *identifier = NSStringFromClass([CommentTableViewCell class]);
        WS(ws);
        height = [tableView fd_heightForCellWithIdentifier:identifier cacheByIndexPath:indexPath configuration:^(id cell) {
            [ws configTableViewCell:cell forIndex:indexPath downloadImage:NO];
        }];
    }
    
    
    height = MAX(height, 45.0f);
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.0f;
    }
    return 10.0f;
}

#pragma mark - config tableviewcell
/**
 *  根据数据模型配置TableViewCell
 *
 *  @param cell      视图
 *  @param indexPath 索引
 *  @param download  是否下载网络图片
 */
- (void)configTableViewCell:(UITableViewCell*)cell forIndex:(NSIndexPath*)indexPath downloadImage:(BOOL)download{
    NSInteger section = indexPath.section;
    if (section == 0) {
        ArticleTableViewCell *tCell = (ArticleTableViewCell*)cell;
        ArticleModel *model = self.articleModel;
        [tCell setArticleInfo:model downloadImage:download];
    } else if (section == 1) {
        CommentTableViewCell *tCell = (CommentTableViewCell*)cell;
        CommentModel *model = [self.mCommentList objectAtIndex:indexPath.row];
        [tCell setCommentInfo:model downloadImage:download];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    
    NSInteger section = indexPath.section;
    if (section == 0) {
        NSString *identifier = NSStringFromClass([ArticleTableViewCell class]);
        ArticleTableViewCell *tCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 收藏
        [tCell.buttonMark handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
            NSLog(@"button mark : {%ld, %ld}", indexPath.section, indexPath.row);
        }];
        // 评论
        [tCell.buttonComment handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
            NSLog(@"button comment : {%ld, %ld}", indexPath.section, indexPath.row);
        }];
        // 踩
        [tCell.buttonHate handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
            NSLog(@"button hate : {%ld, %ld}", indexPath.section, indexPath.row);
        }];
        // 赞
        [tCell.buttonLike handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
            NSLog(@"button like : {%ld, %ld}", indexPath.section, indexPath.row);
        }];
        // 图片 - 单击
        WS(ws);
        [tCell.imageContent handleSingleTapWithBlock:^{
            NSLog(@"image single tap : {%ld, %ld}", indexPath.section, indexPath.row);
            ArticleModel *model = ws.articleModel;
            NSString *fURL = model.thumbnailUrl;
            BOOL bExist = [[SDImageCache sharedImageCache] diskImageExistsWithKey:fURL];
            if (bExist) {
                HYImageBrowser *browser = [XibUtils loadXib:[HYImageBrowser class]];
                [browser setImage:model cell:tCell inTable:tableView];
                [browser show];
            } else {
                NSLog(@"no image can be browsed");
            }
            
        }];
        
        cell = tCell;
    } else if (section == 1) {
        NSString *identifier = NSStringFromClass([CommentTableViewCell class]);
        CommentTableViewCell *tCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        
        cell = tCell;
    }
    
    // Configure the cell...
    [self configTableViewCell:cell forIndex:indexPath downloadImage:YES];
    
    return cell;
}

/**
 *  UITableView滚动回调
 *
 *  @param scrollView
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.inputView dismissKeyboard];
}


#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"didSelectRowAtIndexPath : %@", indexPath);
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

@end
